<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/10
 * Time: 12:01
 */

namespace plugin\admin\app\logic\plan;


use app\common\lib\RedisQueue;
use app\exception\IndexException;
use plugin\admin\app\exception\AdminException;
use plugin\admin\app\logic\BaseLogic;
use plugin\admin\app\model\novel\NovelChapterModel;
use plugin\admin\app\model\plan\NovelChapterPartOverseaModel;
use plugin\admin\app\model\novel\NovelSpreadModel;
use plugin\admin\app\model\plan\PromotionPlanOverseaModel;
use support\Cache;
use support\Request;
use support\Response;

class OverseaPartLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        $this->model = new NovelChapterPartOverseaModel();
    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return new self();
    }

    public function select(Request $request): Response
    {
        $field = $request->input('field');
        if($field==false){
            $request->inputSet('field','number');
            $request->inputSet('order','asc');
        }

        $request->inputSet('isdel','0');
        return parent::select($request);
    }

    protected function formatNormal($items, $total): Response
    {
        $novelMap = $this->getListMapById(NovelSpreadModel::getInstance(),$items,'novel_sn','novel_sn');
        $cahpterMap = $this->getListMapById(NovelChapterModel::getInstance(),$items,'chapterid','id');
        $planMap = $this->getListMapById(PromotionPlanOverseaModel::getInstance(),$items,'planid','id');
        foreach($items as &$val){
            $val['title'] = isset($novelMap[$val['novel_sn']])?$novelMap[$val['novel_sn']]['title']:$val['novel_sn'];
            $val['chaptername'] = isset($cahpterMap[$val['chapterid']])?$cahpterMap[$val['chapterid']]['name']:$val['chapterid'];
            $val['planname'] = isset($planMap[$val['planid']])?$planMap[$val['planid']]['name']:$val['planid'];
            $val['subtitle'] = $val['subtitle'] ? json_decode($val['subtitle'], true) : [];
        }
        return parent::formatNormal($items, $total);
    }

    public function insert(Request $request): Response
    {
        $contents = $request->input('content');
        $request->inputSet('content',json_encode($contents));


        return parent::insert($request);
    }

    protected function doInsert(array $data)
    {
        $data['novel_sn'] = PromotionPlanOverseaModel::getInstance()->getWhere(['id'=>$data['planid']])->value('novel_sn');
        $data['chapterid'] = PromotionPlanOverseaModel::getInstance()->getWhere(['id'=>$data['planid']])->value('chapterid');
        $contents = json_decode($data['content'], true);
        $data['batch'] = date('YmdHis').mt_rand(10,99);

        $insert = [];
        foreach($contents as $k=>$content){
            if(empty($content)){
                continue;
            }
            $insert[] = [
                'planid'=>$data['planid'],
                'novel_sn'=>$data['novel_sn'],
                'chapterid'=>$data['chapterid'],
                'content'=>$content,
                'number'=>$k+1,
                'batch'=>$data['batch'],
            ];
        }

        $insert && NovelChapterPartOverseaModel::getInstance()->getWhere(['planid'=>$data['planid']])->update(['isdel'=>time()]);
        $insert && NovelChapterPartOverseaModel::getInstance()->insert($insert);

        return $this->json(0, 'ok', [count($contents)]);
    }

    public function update(Request $request): Response
    {
        $first = $this->model->find($request->input('id'));
        if($first==false){
            throw new IndexException(4020,'片段不存在');
        }
        if(empty($first['planid'])){
            throw new IndexException(4020,'方案不存在');
        }

        if(!empty($request->input('value'))){
            $value = $request->input('value');
            $data = array_column($value,'value');
            $request->inputSet('subtitle',json_encode($data,256));
        }


        return parent::update($request);
    }

    protected function doUpdate($id, $data)
    {

        return parent::doUpdate($id, $data);
    }

    public function delete(Request $request): Response
    {
        return parent::isDelete($request);
    }

    public function doIsDelete($ids)
    {
        parent::doIsDelete($ids);

        $planid = $this->model->where(['id'=>$ids[0]])->value('planid');
        $batch = $this->model->getWhere(['planid'=>$planid,'isdel'=>0])->max('batch');
        $partNums = $this->model->getWhere(['planid'=>$planid,'isdel'=>0,'batch'=>$batch])->count();
        PromotionPlanOverseaModel::getInstance()->getWhere(['id'=>$planid])->update(['part_nums'=>$partNums]);
    }

    public function generated(Request $request): Response
    {
        if(empty($request->input('planid'))){
            throw new AdminException(4020,'方案不存在');
        }

        //生成唯一的请求id
        $requestId = md5(round(microtime(true)*1000).uniqid().mt_rand(1000,9999));

        // 队列名
        $queue = 'asyncPlanPartOversea';
        // 数据，可以直接传数组，无需序列化
        $data = ['requestid'=>$requestId,'planid'=>$request->input('planid')];
        // 投递消息
        RedisQueue::getInstance()->sendQueue($queue, $data);

        return $this->json('0','ok',['requestid'=>$requestId]);
    }

    public function getProgress(Request $request): Response
    {
        $requestid = $request->input('requestid');
        $cacheKey = 'async_plan_part_oversea_'.$requestid;
        $data = Cache::get($cacheKey);

        return $this->json('0','ok',['progress'=>$data['progress']??0,'error'=>$data['error']??'']);
    }
}